﻿using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Cartographer.Extensions
{
	public static class XDocumentExtensions
	{
		public static T GetAttribute<T>(this XElement element, string attributeName)
		{
			var ret = element.Attribute(attributeName);
			if (ret == null) return default(T);
			return (T)Convert.ChangeType(ret.Value, typeof(T));
		}

		public static T GetAttribute<T>(this XElement element, string attributeName, T defaultValue)
		{
			var ret = element.Attribute(attributeName);
			if (ret == null) return defaultValue;
			return (T)Convert.ChangeType(ret.Value, typeof(T));
		}

		public static T DeserializeWithBinaryData<T>(this XElement element)
		{
			using (var stream = new MemoryStream())
			{
				element.Save(stream);
				stream.Seek(0, SeekOrigin.Begin);
				var serializer = new XmlSerializer(typeof(T));
				return (T)serializer.Deserialize(stream);
			}
		}
	}
}